/**
 * @author 老刘
 * @date 2020/5/16
 * @description 共用函数
 * @version 1.0
 */
let app = getApp();

export function setApp(a) {
	console.log(1);
	app = a;
}
/**
 * 检查更新
 */
export function checkUpdate() {
	if (!wx.canIUse('getUpdateManager')) {
		return;
	}
	const updateManager = wx.getUpdateManager();
	updateManager.onCheckForUpdate((res) => {
		// 有更新
		if (res.hasUpdate) {
			// 下载好后回调
			updateManager.onUpdateReady(() => {
				alert({
					title: '更新提示',
					content: '新版本已经准备好，是否重启应用？',
					confirmText: '重启',
					confirm: () => {
						// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
						updateManager.applyUpdate();
					}
				});
			});
		}
	});
}
/**
 * 获取手机类型
 * @param app
 */
export function getModel(app) {
	const systemInfo = wx.getSystemInfoSync();
	// 获取胶囊信息
	app.globalData.capsule = wx.getMenuButtonBoundingClientRect();
	app.globalData.brand = systemInfo.brand;
	app.globalData.systemInfo = systemInfo;
	app.globalData.mobilePhoneSystem = systemInfo.system.indexOf('iOS') !== -1;
	app.globalData.statusBarHeight = systemInfo.statusBarHeight;
	app.globalData.model = systemInfo.model + '&' + systemInfo.system;
	if (systemInfo.model.toLowerCase().search('iphone x') !== -1) {
		app.globalData.mobilePhoneMode = 1; // iphone x
	} else if (systemInfo.model.toLowerCase().search('iphone') !== -1) {
		app.globalData.mobilePhoneMode = 0; // iphone 678
	} else if (systemInfo.windowHeight * systemInfo.pixelRatio === 1920) {
		app.globalData.mobilePhoneMode = 2; // 1080
	} else {
		app.globalData.mobilePhoneMode = 3; // 安卓全面屏
	}
}
/**
 *  小于10的前补0操作
 * @param n 数字
 */
export const formatNumber = (n) => {
	n = n.toString();
	return n[1] ? n : `0${n}`;
};

/**
 *  格式化时间
 * @param timestamp 日期
 * @returns {string} 返回结果字符串类型
 */
export function formatTime (timestamp) {
	if(timestamp.toString().length !== 13){
		timestamp = timestamp * 1000;
	}
	const date = new Date(timestamp);
	const year = date.getFullYear();
	const month = date.getMonth() + 1;
	const day = date.getDate();
	const hour = date.getHours();
	const minute = date.getMinutes();
	const second = date.getSeconds();
	return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second].map(formatNumber).join(':')}`;
}
/**
 *  初始化图表
 */
export function initializationEcharts($event, echarts, getOption){
	$event.init((canvas, width, height, dpr) => {
		// 初始化图表
		const Chart = echarts.init(canvas, null, {
			width: width + 60,
			height: height + 60,
			devicePixelRatio: dpr // new
		});
		Chart.setOption(getOption);
		// 注意这里一定要返回 chart 实例，否则会影响事件处理等
		return Chart;
	});
}
/**
 * px转rpx
 * @param px
 */
function pxHalfRpx (px) {
	return px / 750 * wx.getSystemInfoSync().windowWidth;
}
/**
 * rpx转px
 * @param rpx
 */
export function rpx2px(rpx) {
	return rpx / 750 * wx.getSystemInfoSync().windowWidth;
}

export function wxAnimation(delay, site, translate, opacity = 1) {
	site = pxHalfRpx(site);
	const animation = wx.createAnimation({
		delay,
		duration: 300,
		timingFunction: 'ease-in'
	});
	if (translate === 'translateY') {
		animation.translateY(site).opacity(opacity).step();
	} else {
		animation.translateX(site).step();
	}
	return animation.export();
}
/**
 *  跳转到url
 * @param url
 */
export function go(url) {
	wx.navigateTo({
		url: url
	});
}
/**
 * 微信api回调形式转为promise调用形式
 * @param target
 * @param params
 * @param args
 */
export function wxApi2Promise(target, params = {}, ...args) {
	return new Promise((resolve, reject) => {
		params['success'] = (res) => {
			resolve(res);
		};
		params['fail'] = (error) => {
			reject(error);
		};
		target(params,...args);
	});
}
/**
 *  获取微信api返回
 *  @param target
 *  @param scope
 *  @param args
 */
export function wxApiPromise(target, scope = '', ...args) {
	const params = {};
	return new Promise((resolve, reject) => {
		params['success'] = (res) => {
			args.length && args[0].setData({
				showLoading: false
			});
			resolve(res);
		};
		params['fail'] = async (error) => {
			if (scope && !await haveAuth(`scope.${scope}`)) {
				authorizationUserInfo(scope, args);
				return;
			}
			args.length && args[0].setData({
				showLoading: false
			});
			reject(error);
		};
		target(params,...args);
	});
}
/**
 * 授权获取用户信息
 * @param scope
 * @param args
 */
function authorizationUserInfo (scope, args) {
	const list = [
		{scope: 'werun', content: '检查您未授权获取微信步数,请授权'},
		{scope: 'userLocation', content: '检查您未授权获取地理位置,请授权'}
	];
	const info = list.find(item => scope === item.scope);
	alert({
		content: info.content,
		showCancel: true,
		confirmText: '授权',
		confirm: async () => {
			await openSetting();
		},
		cancel: async () => {
			args.length && args[0].setData({
				showLoading: false
			});
		}
	});
}
/**
 * 打开微信小程序设置界面
 */
export function openSetting() {
	return wxApiPromise(wx.openSetting);
}
/**
 * 获取小程序授权
 */
export function getSetting() {
	return wxApiPromise(wx.getSetting);
}
/**
 * 判断用户是否进行授权
 * @param scope
 */
export async function haveAuth(scope) {
	let haveAuth = false;
	const res = await getSetting();
	if (res.errMsg === 'getSetting:ok' && res.authSetting) {
		if (res.authSetting[scope] === true) {
			haveAuth = true;
		}
	}
	return haveAuth;
}
/**
 *  获取云函数返回值
 *  @param name 云函数名
 *  @param params 参数
 */
export function getCloudFunctionData(name, params) {
	if (!wx.cloud) {
		showToastNoIcon('请使用 2.2.3 或以上的基础库以使用云能力');
		return;
	} else {
		wx.cloud.init({
			env: 'laoliu-xiaochengxu-3fe40b',// 环境ID
			traceUser: true
		});
	}
	return new Promise((resolve, reject) => {
		wx.cloud.callFunction({
			// 云函数名称
			name: name,
			// 传给云函数的参数
			data: params,
			success: (res) => {
				resolve(res);
			},
			fail: (error) => {
				reject(error);
			}
		})
	});
}
/**
 *  弹出吐司提示 不带icon
 * @param content 提示内容
 */
export function showToastNoIcon(content) {
	setTimeout(() => {
		wx.showToast({
			title: content,
			icon: 'none',
			duration: 2000
		});
	}, 100);
}
// 是否为json
export function isJsonString(str) {
	try {
		if (typeof JSON.parse(str) === 'object') {
			return true;
		}
	} catch (e) {
		return false;
	}
	return false;
}

// 弹窗
export function alert({
	               title = '提示',
	               content = '描述信息',
	               showCancel = false,
	               confirmText = '我知道了',
	               cancelText = '取消',
	               confirmColor = '$fontColor',
	               cancelColor = '#99999D',
	               confirm = () => {
	               },
	               cancel = () => {
	               }
               } = {}) {
	wx.showModal({
		title: title,
		content: content,
		showCancel: showCancel,
		confirmText: confirmText,
		cancelText: cancelText,
		confirmColor: confirmColor,
		cancelColor: cancelColor,
		success(res) {
			if (res.confirm) {
				confirm();
			} else if (res.cancel) {
				cancel();
			}
		}
	});
}

// 加载中。。。
export function showLoading({
	                     title = '加载中...',
	                     mask = true
                     } = {}) {
	wx.showLoading({
		title: title,
		mask: mask
	});
}

export function hideLoading() {
	wx.hideLoading();
}

// 根据日期计算汉字
export function getDateDiff(dateTimeStamp) {
	let result = '';
	let minute = 1000 * 60;
	let hour = minute * 60;
	let day = hour * 24;
	let halfamonth = day * 15;
	let month = day * 30;
	let now = new Date().getTime();
	let diffValue = now - dateTimeStamp;
	if (diffValue < 0) {
		return;
	}
	let monthC = diffValue / month;
	let weekC = diffValue / (7 * day);
	let dayC = diffValue / day;
	let hourC = diffValue / hour;
	let minC = diffValue / minute;
	if (monthC >= 1) {
		result = "" + parseInt(monthC) + "月前";
	} else if (weekC >= 1) {
		result = "" + parseInt(weekC) + "周前";
	} else if (dayC >= 1) {
		result = "" + parseInt(dayC) + "天前";
	} else if (hourC >= 1) {
		result = "" + parseInt(hourC) + "小时前";
	} else if (minC >= 1) {
		result = "" + parseInt(minC) + "分钟前";
	} else
		result = "刚刚";
	return result;
}

// 将号码中间四位替换为*
export function mobilePhoneReplace(res) {
	if (!res) return '';
	let reg = /(\d{3})\d{4}(\d{4})/ig;
	return res.replace(reg, '$1****$2')
}

// 比较微信基础库版本
export function compareVersion(v1, v2) {
	v1 = v1.split('.');
	v2 = v2.split('.');
	const len = Math.max(v1.length, v2.length);

	while (v1.length < len) {
		v1.push('0');
	}
	while (v2.length < len) {
		v2.push('0');
	}

	for (let i = 0; i < len; i++) {
		const num1 = parseInt(v1[i]);
		const num2 = parseInt(v2[i]);

		if (num1 > num2) {
			return 1;
		} else if (num1 < num2) {
			return -1;
		}
	}
	return 0;
}

/**
 * @author い 老刘
 * @param bankno 银行卡号
 * @returns {boolean} 是银行卡号返回 true 否则false
 * @description 银行卡号验证
 */
export function luhmCheck(bankno) {
	if (bankno.length < 16 || bankno.length > 19) {
		return false;
	}
	// 全数字
	let num = /^\d*$/;
	if (!num.exec(bankno)) {
		return false;
	}
	// 开头6位
	let strBin = '10,18,30,35,37,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,58,60,62,65,68,69,84,87,88,94,95,98,99';
	if (strBin.indexOf(bankno.substring(0, 2)) === -1) {
		return false;
	}
	let lastNum = parseInt(bankno.substr(bankno.length - 1, 1)); // 取出最后一位（与luhm进行比较）

	let first15Num = bankno.substr(0, bankno.length - 1); // 前15或18位
	let newArr = [];
	for (let i = first15Num.length - 1; i > -1; i--) { // 前15或18位倒序存进数组
		newArr.push(first15Num.substr(i, 1));
	}
	// 奇数位*2的积 <9
	let arrJiShu = [];
	// 奇数位*2的积 >9
	let arrJiShu2 = [];
	// 偶数位数组
	let arrOuShu = [];
	for (let j = 0; j < newArr.length; j++) {
		if ((j + 1) % 2 === 1) { // 奇数位
			if (parseInt(newArr[j]) * 2 < 9) {
				arrJiShu.push(parseInt(newArr[j]) * 2);
			} else {
				arrJiShu2.push(parseInt(newArr[j]) * 2);
			}
		} else { // 偶数位
			arrOuShu.push(newArr[j]);
		}
	}

	let jishuChild1 = []; // 奇数位*2 >9 的分割之后的数组个位数
	let jishuChild2 = []; // 奇数位*2 >9 的分割之后的数组十位数
	for (let h = 0; h < arrJiShu2.length; h++) {
		jishuChild1.push(parseInt(arrJiShu2[h]) % 10);
		jishuChild2.push(parseInt(arrJiShu2[h]) / 10);
	}

	let sumJiShu = 0; // 奇数位*2 < 9 的数组之和
	let sumOuShu = 0; // 偶数位数组之和
	let sumJiShuChild1 = 0; // 奇数位*2 >9 的分割之后的数组个位数之和
	let sumJiShuChild2 = 0; // 奇数位*2 >9 的分割之后的数组十位数之和
	let sumTotal = 0;
	for (let m = 0; m < arrJiShu.length; m++) {
		sumJiShu = sumJiShu + parseInt(arrJiShu[m]);
	}

	for (let n = 0; n < arrOuShu.length; n++) {
		sumOuShu = sumOuShu + parseInt(arrOuShu[n]);
	}

	for (let p = 0; p < jishuChild1.length; p++) {
		sumJiShuChild1 = sumJiShuChild1 + parseInt(jishuChild1[p]);
		sumJiShuChild2 = sumJiShuChild2 + parseInt(jishuChild2[p]);
	}
	// 计算总和
	sumTotal = parseInt(sumJiShu) + parseInt(sumOuShu) + parseInt(sumJiShuChild1) + parseInt(sumJiShuChild2);

	// 计算Luhm值
	let k = parseInt(sumTotal) % 10 === 0 ? 10 : parseInt(sumTotal) % 10;
	let luhm = 10 - k;

	return lastNum === luhm;
}

/**
 * 返回首页
 */
export function goHome(unload) {
	let len = getCurrentPages().length;
	let delta = unload ? len - 2 : len - 1;
	if (delta > 0) {
		wx.navigateBack({
			delta: delta // 默认值是1
		});
	}
}
/**
 * 小写数字转大写
 * @param n
 * @returns {number}
 */
export const lowercaseToUppercase = function(n) {
	const cnum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
	let s = '';
	n = '' + n; // 数字转为字符串
	for (let i = 0; i < n.length; i++) {
		s += cnum[parseInt(n.charAt(i))];
	}
	if (s.length === 2) { // 两位数的时候
		// 如果个位数是0的时候，令改成十
		if (s.charAt(1) === cnum[0]) {
			s = s.charAt(0) + cnum[10];
			// 如果是一十改成十
			if (s === cnum[1] + cnum[10]) {
				s = cnum[10];
			}
		} else if (s.charAt(0) === cnum[1]) {
			// 如果十位数是一的话改成十
			s = cnum[10] + s.charAt(1);
		}
	}
	return s;
};
/**
 *  初始化时间
 */
export function initializationDate(choiceData, app){
	let isShowPre = true;
	let isShowNext = false;
	if (choiceData.length === 8) {
		// 选择日期
		isShowPre = choiceData !== `${app.globalData.startDateYear}${formatNumber(app.globalData.startDateMonth)}01`;
		isShowNext = choiceData < getModifyTime(getTimeStr(), -1);
	} else {
		// 选择月份
		isShowPre = choiceData !== `${app.globalData.startDateYear}${formatNumber(app.globalData.startDateMonth)}`;
		isShowNext = choiceData < getModifyTime(getTimeStr('month'), 0);
	}
	console.log(isShowPre,isShowNext)
	return {isShowPre,isShowNext};
}
/**
 *  获取某一天的前一天 或者 后一天的时间
 *  preOrNext  -1 前一天|月   1 后一天|月
 */
export function getModifyTime(someday,preOrNext = 1){
	someday = someday || new Date;
	if (someday.length === 8) {
		let date = `${someday.substring(0, 4)}-${someday.substring(4, 6)}-${someday.substring(6, 8)}`;
		let dd = new Date(date);
		dd.setDate(dd.getDate() + preOrNext);
		let y = dd.getFullYear();
		let m = dd.getMonth() + 1 < 10 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1;
		let d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
		return `${y}${m}${d}`;
	} else {
		let date = `${someday.substring(0, 4)}-${someday.substring(4, 6)}`;
		var dd = new Date(date);
		dd.setMonth(dd.getMonth() + preOrNext);
		let y = dd.getFullYear();
		let m = dd.getMonth() + 1 < 10 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1;
		return `${y}${m}`;
	}
}
/**
 *  获取当前时间字符串
 */
export function getTimeStr(type = 'day'){
	let now = new Date();
	let year = now.getFullYear();
	let month = now.getMonth() + 1;
	if (type === 'day') {
		return `${year}${formatNumber(month)}${formatNumber(now.getDate())}`;
	} else {
		return `${year}${formatNumber(month)}`;
	}
}
